home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: news.uunet.ca!wildcan!sq!msb
- From: msb@sq.com (Mark Brader)
- Subject: Re: Determining the length of an int in string form
- Message-ID: <1996Mar24.195142.14175@sq.com>
- Organization: SoftQuad Inc., Toronto, Canada
- References: <3146D058.DD7@cbm.com> <4ipd9k$ep8@news.erinet.com> <Pine.SOL.3.91.960320230310.14476C-100000@darwin.UCSC.EDU> <Pine.SOL.3.91.960321120638.3532A-100000@darwin.UCSC.EDU>
- Date: Sun, 24 Mar 1996 19:51:42 GMT
-
- If the motivation for the question is simply to find out how large a
- buffer you need to use to sprintf() the int into it, then don't bother.
-
- Just use a buffer of (sizeof(int) * CHAR_BIT + 2) / 3 + 1 + 1 bytes,
- like it says in the FAQ list, and you're done. The only problem would
- be if you're still using a pre-ANSI system and don't have CHAR_BIT
- available; in that case I'd suggest finding out what it is (that's
- trivial) and providing it through a system-dependent header file of
- your own, or of course, getting a newer C implementation.
-
- If you actually need to store a whole bunch of ints and are concerned
- about space efficiency, then store them *as* ints, not strings.
-
- If this is really only part of the question and you actually need to
- store a whole lot of strings each of which contains the string version
- of an int as part of its content, then this technique:
-
- "royaltey@darwin.UCSC.EDU" writes:
- > Another alternative is to sprintf the string into a static buffer
- > known to be long enough to hold any int, strlen the result to find the
- > actual length, malloc a suitably sized buffer, then strcpy the result
- > to the malloc'ed buffer.
-
- (with the appropriate modification for your actual situation) is generally
- the best and easiest.
-
- However, note that there may actually be no difference betwen malloc()ing,
- say, 5 bytes for this string and 8 bytes for that one. That is, it's
- entirely possible that malloc() rounds the number of bytes allocated up
- to a multiple of some convenient amount. In general, it's not worth
- sweating to get malloc()ed storage down to the exact minimum size that
- the data being stored really needs, if it's any trouble to calculate it.
-
- Maurizio Loreti (loreti@padova.infn.it)'s suggestion in another branch of
- the thread:
-
- | However, the solution is to fprintf the integer to the bit bucket
- | (i.e. /dev/null, NLA0:, NIL or what is called on your system) and to
- | use its return value.
-
- is also feasible, but inherently system-dependent, and fails on systems
- that don't *have* a bit bucket.
-
- --
- Mark Brader We say, "But it wasn't designed to do that!";
- SoftQuad Inc. our managers say, "Our customers want this!";
- msb@sq.com we say, "Small is beautiful!"; and they say,
- Toronto "Money is beautiful!" -- Andrew Tannenbaum
-
- My text in this article is in the public domain.
-